package com.ruyuan.seckilling.render.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruyuan.seckilling.common.ChannelKey;
import com.ruyuan.seckilling.common.QueueKey;
import com.ruyuan.seckilling.render.async.PageRenderContext;
import com.ruyuan.seckilling.render.async.PageRenderEventHolder;
import com.ruyuan.seckilling.render.config.BussinessConfig;
import com.ruyuan.seckilling.render.entity.PageLog;
import com.ruyuan.starter.async.BossEventBus;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = QueueKey.QUEUE_RENDER_PAGE, consumerGroup = "rendPageConsumer")
public class RenderPageListener implements RocketMQListener<String> {

    @Autowired
    private BossEventBus bossEventBus;

    // 消息格式示例
    // .pageCode("seckilling_product")
    // .bizData(ImmutableMap.of("type", "product", "activityId", id, "skuId", skuId))
    // .params(ImmutableMap.of("activityId", id, "skuId", skuId))
    // .fileName(FileNameUtils.generateSeckillingProductFilename(skuId))
    @Override
    public void onMessage(String messageString) {

        log.info("收到渲染页面的消息, message={}", messageString);

        try {
            JSONObject message = JSONObject.parseObject(messageString);

            PageRenderContext context = new PageRenderContext();
            context.setPageCode(message.getString("pageCode"));
            context.setBizData(message.getJSONObject("bizData"));
            context.setParams(message.getJSONObject("params"));
            context.setFileName(message.getString("fileName"));

            context.setPageLog(new PageLog());
            context.getPageLog().setStartTime(System.currentTimeMillis());
            context.getPageLog().setBizData(JSON.toJSONString(context.getBizData()));
            context.getPageLog().setOpType("render");
            context.getPageLog().setFileName(context.getFileName());
            context.getPageLog().setServerIps(BussinessConfig.getNginxServerIps());
            context.getPageLog().setMsg(messageString);

            bossEventBus.publish(ChannelKey.CHANNEL_01_LOAD_PAGE_CONFIG, PageRenderEventHolder.EVENT_01, context);
        } catch (Exception ignore) {
        }
    }
}
